from PIL import Image
from numpy.typing import NDArray
import os
import json
import pickle

def read_image(image_path) -> Image.Image:
    # return np.asarray(Image.open(image_path))
    return Image.open(image_path)

def save_numpy_as_rgb_image(path, np_image: NDArray, color_mode='RGB', force=False):
    if force or not os.path.exists(path):
        if np_image.dtype != 'uint8':
            print(f'WARN: numpy array converted to image while dtype is {np_image.dtype}')
        img = Image.fromarray(np_image.astype('uint8'), mode=color_mode)
        img.save(path)
    else:
        print(f"INFO: {path} already exist, image file un-written!")

def read_json(path):
    with open(path, 'r') as f:
        return json.load(f)

def write_json(path, data, force=False) -> None:
    """ write data to json file of path
    :param path: path of json file, should include json file name in the path
    :param data: data to write
    :param force: if force writing if path exists
    """
    if force or not os.path.exists(path):
        with open(path, 'w') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
            print(f"INFO: {path} is written")
    else:
        print(f"INFO: {path} already exist, json file un-written!")

def read_pickle(path):
    with open(path, 'rb') as f:
        return pickle.load(f)

def write_pickle(path, data, force=False) -> None:
    if force or not os.path.exists(path):
        with open(path, 'wb') as f:
            pickle.dump(data, f)
            print(f"INFO: {path} is written")
    else:
        print(f"INFO: {path} already exist, pickle file un-written!")
